<script setup lang="ts">
import TableHead from './TableHead.vue'
import ReportPerson from './ReportPerson.vue'

import type { LoadListParams } from './types'
import useAll from './useAll'
import { uuid } from '@/utils'
import { loadGoalCompletionStatus } from '@/api/modules/enterpriseQuarterlyReport'
import { useStatementStore } from '@/store'

const P = '单位产品综合能耗进度节能量目标完成率'
const Q = '产值综合能耗进度节能量目标完成率'
const R = '进度节能量目标完成情况说明'

const readonly = computed(() => {
  const statementStore = useStatementStore()
  return statementStore.readonly
})
const description = ref({
  key: 'oneYear',
  value: '',
  editable: true,
})

watchEffect(() => {
  description.value.editable = !readonly.value
})

const calc = computed(() => {
  const keys = [
    'oneYear',
    'twoYear',
    'threeYear',
    'fourYear',
    'fiveYear',
  ]
  const prefix = [P, Q]
  const listsValue = lists.value
  // 进度节能量目标
  const t1 = listsValue[0]?.data
  // 单位产品综合能耗实际完成进度节能量
  const t2 = listsValue[1]?.data
  // 产值综合能耗实际完成进度节能量
  const t3 = listsValue[2]?.data

  if (!t1 || !t2 || !t3)
    return {}
  const calculate = (
    a: number | string,
    b: number | string,
  ) => {
    const n = +((100 * +a) / +b).toFixed(2)
    return Number.isFinite(n) ? n : ''
  }
  // 单位产品综合能耗进度节能量目标完成率 =
  // (单位产品综合能耗实际完成节能量 ÷ 进度节能量目标) × 100%

  // 产值综合能耗进度节能量目标完成率 =
  // (产值综合能耗实际完成节能量 ÷ 进度节能量目标) × 100%
  const obj: any = {}
  for (const r of prefix) {
    for (const k of keys) {
      const key = r + k
      const v1 = (r === P ? t2 : t3).find(
        vv => vv.key === k,
      )
      const v2 = t1.find(vv => vv.key === k)
      obj[key] = calculate(
        v1 ? v1.value : '',
        v2 ? v2.value : '',
      )
    }
  }
  return obj
})

async function request(params: LoadListParams) {
  const { data, ...rest } = await loadGoalCompletionStatus(params)
  if (data.length === 0) {
    const projects = [
      {
        projectName: '进度节能量目标',
        unitOfMeasurement: '吨标准煤',
        code: '01',
      },
      {
        projectName: '单位产品综合能耗实际完成进度节能量',
        unitOfMeasurement: '吨标准煤',
        code: '02',
      },
      {
        projectName: '产值综合能耗实际完成进度节能量',
        unitOfMeasurement: '吨标准煤',
        code: '03',
      },
      {
        projectName: '单位产品综合能耗进度节能量目标完成率',
        unitOfMeasurement: '%',
        code: '04',
      },
      {
        projectName: '产值综合能耗进度节能量目标完成率',
        unitOfMeasurement: '%',
        code: '05',
      },
    ]
    return {
      data: projects,
      ...rest,
    }
  }

  const findIndex = data.findIndex(
    (v: any) => v.projectName === R,
  )
  if (findIndex > -1) {
    // 进度节能量目标完成情况说明 (存取字段为 oneYear)
    const item = data.splice(findIndex, 1)[0] as any

    // Set description
    description.value = {
      key: 'oneYear',
      value: item.oneYear,
      editable: !readonly.value,
    }
  }
  return { data, ...rest }
}

const {
  columns,
  title,
  lists,
  informant,
  clickCallback,
  loadPrevList,
  report,
  saveStage,
  exportFile,
} = useAll(request, {
  transfer(
    data: any,
    { statementFlattenColumns: flattenColumns, readonly },
  ) {
    return data.map((v: any) => {
      const d = flattenColumns.map((vv) => {
        const key = vv.prop
        const value = String(v[key] || '')
        let editable = true
        let calculable
        let calculationKey
        if (readonly) {
          return {
            key,
            value,
            editable: false,
          }
        }
        if (
          [
            'projectName',
            'unitOfMeasurement',
            'code',
          ].includes(key)
        ) {
          editable = false
        }
        if ([P, Q].includes(v.projectName)) {
          editable = false
          if (
            [
              'oneYear',
              'twoYear',
              'threeYear',
              'fourYear',
              'fiveYear',
            ].includes(key)
          ) {
            calculable = true
            calculationKey = v.projectName + key
          }
        }
        return {
          key,
          value,
          editable,
          calculable,
          calculationKey,
        }
      })
      return {
        uuid: uuid(),
        data: d,
        informant: {
          personInCharge: v.personInCharge,
          informer: v.informer,
          telephone: v.telephone,
          fillInDate: v.fillInDate,
        },
      }
    })
  },
  getCalc(
    row: number,
    prop: string,
    value?: string | number | undefined,
  ) {
    // 单位产品综合能耗进度节能量目标完成率 3
    // 产值综合能耗进度节能量目标完成率 4
    let key = ''
    if (row === 3) {
      key = P + prop
    }
    else if (row === 4) {
      key = Q + prop
    }
    else {
      return value
    }
    return typeof calc.value[key] === 'undefined'
      ? value
      : String(calc.value[key] || '')
  },
  assignExtraData(params, { data, state, illustrate }) {
    // 进度节能目标完成情况表
    // 进度节能量目标完成情况说明
    const item = data[0] || {}
    console.log('item: ', item)
    params.list.push({
      ...item,
      projectName: '进度节能量目标完成情况说明',
      oneYear: toValue(description).value || '',
      state,
      illustrate,
    })
  },
  lengthPerRow: 5,
})
</script>

<template>
  <div
    class="width-100 height-100 statement-table position-relative overflow-hidden"
  >
    <slot
      name="title"
      :title="title"
      :report="report"
      :load-prev-list="loadPrevList"
      :save-stage="saveStage"
      :export-file="exportFile"
    >
      <h2 class="table-title">
        {{ title }}
      </h2>
    </slot>
    <div class="report-table-head">
      <table class="report-table">
        <TableHead
          :columns="columns"
          :show-line-number="false"
        />
      </table>
    </div>
    <ElScrollbar
      class="bg-color"
      style="height: calc(100% - 90px)"
      wrap-style="overflow-x: hidden;"
    >
      <table class="report-table">
        <tbody ref="tbody">
          <tr v-for="item in lists" :key="item.uuid">
            <td
              v-for="(d, index) in item.data"
              :key="item.uuid + index"
              :class="{
                'is-calculable':
                  d.calculable && d.calculationKey,
              }"
              :style="index === 0 ? 'width:300px;' : ''"
            >
              <div v-if="!d.editable" class="span-cell">
                {{
                  d.calculable && d.calculationKey
                    ? calc[d.calculationKey]
                    : d.value
                }}
              </div>
              <div v-else class="input-cell">
                <input
                  v-model="d.value"
                  type="text"
                  @click="clickCallback"
                >
              </div>
            </td>
          </tr>
          <tr>
            <td colspan="3">
              <div class="span-cell big-td">
                进度节能量目标完成情况说明
              </div>
            </td>
            <td colspan="5">
              <div
                v-if="!description.editable"
                class="span-cell"
              >
                {{ description.value }}
              </div>
              <div v-else class="input-cell">
                <textarea
                  v-model="description.value"
                  :readonly="readonly"
                  @click="clickCallback"
                />
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="fill-description">
        <ReportPerson
          v-model="informant"
        />
        <p>说明：</p>
        <p>
          1．本表进度节能量目标指节能主管部门根据“十二五”节能量目标和时间进度要求核定的进度节能量目标。
        </p>
        <p>
          2．实际完成节能量指2011年至本年度累计完成节能量；各年节能量按年度环比计算。
        </p>
        <p>
          3．进度节能量目标完成率=（实际完成节能量÷进度节能量目标）×100%。
        </p>
        <p>
          4．对进度节能量目标完成情况给予说明，字数应在100个汉字以内。
        </p>
      </div>
    </ElScrollbar>
  </div>
</template>
